package com.block.datapush.service.apipush;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.HttpApiUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YiShiDaiSsqUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * e时代双授权
 */
@Service
public class YiShiDaiSsqApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String apiKey = pushApiKeyParam.getApiKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("userName", memberSourceInfo.getRealname());
        bizMap.put("sex", YiShiDaiSsqUtil.getSex(memberSourceInfo.getSex()));

        bizMap.put("age", String.valueOf(memberSourceInfo.getAge()));

        bizMap.put("phoneMd5", mobileMd5);
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("overdue", YiShiDaiSsqUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("carInfo", YiShiDaiSsqUtil.getCar(memberSourceInfo.getYuqi()));
        bizMap.put("loanAmount", YiShiDaiSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("bizLicenseYear", "1");
        bizMap.put("hbLimit", YiShiDaiSsqUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("sesameCredit", YiShiDaiSsqUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("career", YiShiDaiSsqUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("socialSecurity", YiShiDaiSsqUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("btLimit", YiShiDaiSsqUtil.getBaitiao(memberSourceInfo.getShebao()));
        bizMap.put("realEstateInfo", YiShiDaiSsqUtil.getHouse(memberSourceInfo.getHouse()));

        bizMap.put("providentFund", YiShiDaiSsqUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("creditLimit", YiShiDaiSsqUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        bizMap.put("insurancePolicy", YiShiDaiSsqUtil.getbaodan(memberSourceInfo.getBaoxian()));

        String aesKey = pushApiKeyParam.getApiSecret();
        YiShiDaiSsqUtil yiShiDaiSsqUtil = BeanUtil.mapToBean(bizMap, YiShiDaiSsqUtil.class, true);
        Long timestamp = System.currentTimeMillis();
        String body = this.getDataJson(yiShiDaiSsqUtil);
        String s = SecureUtil.md5(new StringBuilder(body).append(apiKey).append(String.valueOf(timestamp)).toString());

        //加密
//        String encrypt =  SecureUtil.aes(aesKey.getBytes()).encryptBase64(body);

        String encrypt = this.encryptData(aesKey, body);

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("client-id", apiKey);
        paramMap.put("service-code", "A0001");
        paramMap.put("sign", s);
        paramMap.put("timestamp", String.valueOf(timestamp));

        log.info("【e时代下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpApiUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .headerMap(paramMap,true)
                .body(encrypt)
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【e时代下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 0) {
            JSONObject data1 = resultObject.getJSONObject("data");

                String companyLogo = data1.getString("companyLogo");
                String companyName = data1.getString("companyName");
                String productName = data1.getString("productName");
                String price = data1.getString("price");
                JSONArray protocolList = data1.getJSONArray("protocolList");

                JSONObject data = protocolList.getJSONObject(0);
                String protocolName = data.getString("protocolName");//协议名称
                String protocolNameUrl = data.getString("protocolNameUrl");//协议地址

                // 撞库成功之后，商户的机构数据存储

                ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
                thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
                thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
                thirdInfoDTO.setOrderNo(orderNo);
                String tid = UUID.randomUUID().toString();
                JSONObject infoObject = new JSONObject();
                infoObject.put("orderNo",tid);
                infoObject.put("productId",tid);
                infoObject.put("productName",productName);
                infoObject.put("companyName",companyName);
                infoObject.put("companyLogo",companyLogo);
                infoObject.put("maxLoanAmount","20000");
                infoObject.put("maxLoanRate","24");
                infoObject.put("minLoanRate","12");
                infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocalName",protocolName);
                jsonObject.put("protocalUrl",protocolNameUrl);
                jsonArray.add(jsonObject);
                infoObject.put("protocalList",jsonArray);
                thirdInfoDTO.setInfoObject(infoObject);

                boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
                if (save){
                    pushApiResult.setPushSuccess(true);
                    pushApiResult.setOutOrderNo(tid);
                    extJson.put("tid", tid);
                }else{
                    pushApiResult.setMessage("保存撞库数据失败");
                }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String mobile = memberSourceInfo.getMobile();
        String apiKey = pushApiKeyParam.getApiKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("sex", YiShiDaiSsqUtil.getSex(memberSourceInfo.getSex()));

        bizMap.put("age", String.valueOf(memberSourceInfo.getAge()));

        bizMap.put("phone", mobile);
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("userName", memberSourceInfo.getRealname());
        String reqIp = memberSourceInfo.getReqIp();
        if (StringUtils.isNotEmpty(reqIp)){
            bizMap.put("ip", reqIp);
        }else {
            bizMap.put("ip", "127.0.0.1");
        }
        bizMap.put("overdue", YiShiDaiSsqUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("carInfo", YiShiDaiSsqUtil.getCar(memberSourceInfo.getYuqi()));
        bizMap.put("loanAmount", YiShiDaiSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("bizLicenseYear", "1");
        bizMap.put("hbLimit", YiShiDaiSsqUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("sesameCredit", YiShiDaiSsqUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("career", YiShiDaiSsqUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("socialSecurity", YiShiDaiSsqUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("btLimit", YiShiDaiSsqUtil.getBaitiao(memberSourceInfo.getShebao()));
        bizMap.put("realEstateInfo", YiShiDaiSsqUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("providentFund", YiShiDaiSsqUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("creditLimit", YiShiDaiSsqUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        bizMap.put("insurancePolicy", YiShiDaiSsqUtil.getbaodan(memberSourceInfo.getBaoxian()));

        String aesKey = pushApiKeyParam.getApiSecret();
        YiShiDaiSsqUtil yiShiDaiSsqUtil = BeanUtil.mapToBean(bizMap, YiShiDaiSsqUtil.class, true);
        Long timestamp = System.currentTimeMillis();
        String body = this.getDataJson(yiShiDaiSsqUtil);
        String s = SecureUtil.md5(new StringBuilder(body).append(apiKey).append(String.valueOf(timestamp)).toString());

        //加密
        String encrypt = this.encryptData(aesKey, body);

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("client-id", apiKey);
        paramMap.put("service-code", "A0002");
        paramMap.put("sign", s);
        paramMap.put("timestamp", String.valueOf(timestamp));

        log.info("【e时代下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .headerMap(paramMap,true)
                .body(encrypt)
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【e时代下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 0){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 0) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    private <T> String getDataJson(T data) {
         // 字段排序
         TreeMap<String, T> treeMap = new TreeMap<String, T>();
         ReflectUtil.getFieldMap(data.getClass()).forEach((k, v) -> {
             treeMap.put(k, (T) ReflectUtil.getFieldValue(data, v));
             });
         // 业务数据
         return JSONObject.toJSONString(treeMap);
    }

    private <T> String encryptData(String privateKey, String
            dataJson) {
        Map<String, String> dataMap = MapUtil.newHashMap(16);
        AES aes = new AES(HexUtil.decodeHex(privateKey));
        // 业务数据
        dataMap.put("data", aes.encryptHex(dataJson));
        return JSONObject.toJSONString(dataMap);
        }

}
